/* eslint-disable no-unused-vars */
/*
 * @Author: Season
 * @Date: 2020-08-11 15:47:41
 * @LastEditTime: 2020-08-12 11:43:17
 * @FilePath: \blog-chain\src\httpServe.ts
 */
import * as WebSocket from 'ws';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import BlockChain from './blockChain';

const httpServe = (port: number, sockets: WebSocket[], blockChain: BlockChain) => {
  const app = express();
  app.use(bodyParser.json());
  app.get('/', (req, res) => res.send(blockChain));

  // app.get('/peers', (req, res) => {
  //   res.send(sockets.map((s) => `${s.remoteAddress}:${s.remotePort}`));
  // });

  app.post('/mine', (req, res) => {
    const newBlock = blockChain.generateNextBlock(req.body.data);
    blockChain.addBlock(newBlock);
    sockets.forEach((socket) => {
      socket.send(JSON.stringify({ type: 'mine', data: blockChain }));
    });

    res.send();
    // res.send(sockets.map((s) => `${s.remoteAddress}:${s.remotePort}`));
  });

  app.listen(port, () => console.log(`listening on port ${port}!`));
};

export default httpServe;
